package com.hyts.infodb.utils;

import com.alibaba.fastjson.JSONObject;
import com.hyts.infodb.config.SpringContextConfiguration;
import lombok.Getter;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;

/**
 * project-name:infodb
 * package-name:com.hyts.infodb.utils
 * author:Libo/Alex
 * create-date:2019-05-19 14:18
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于:
 */
public class RedisUtils {

    //@Getter
    //private final StringRedisTemplate stringRedisTemplate;

    @Getter
    private final RedisTemplate<String,Object> redisTemplate;

    private static Object lock = new Object();

    private static RedisUtils redisUtils = null;

    /**
     * redis 构造器-服务
     */
    {
        //stringRedisTemplate = SpringContextConfiguration.getGlobalBean(StringRedisTemplate.class);
        redisTemplate = (RedisTemplate<String, Object>) SpringContextConfiguration.getGlobalBean("customRedisTemplate");
    }

    private RedisUtils(){}

    /**
     * 单例模式
     * @return
     */
    public static RedisUtils me(){
        //redis服务
        if(redisUtils == null){
            synchronized (lock){
                if(redisUtils == null){
                    redisUtils = new RedisUtils();
                }
            }
        }
        return redisUtils;
    }

    /**
     * 获取value根据key
      * @param key
     * @return
     */
    public Object get(Object key){
       return redisTemplate.opsForValue().get(key);
    }

    /**
     * @param key
     * @param value
     * @return
     */
    public Object set(Object key,Object value){
        System.out.println(JSONObject.toJSONString(value));
        redisTemplate.opsForValue().set((String) key,value);
        return value;
    }

    /**
     * @param key
     * @return
     */
    public boolean del(Object key){
        return redisTemplate.delete((String) key);
    }

    /**
      * @param keys
     * @return
     */
    public long dels(Collection keys){
        return redisTemplate.delete(keys);
    }

    /**
     * @return
     */
    public Set<?> getKeys(String cacheName){
        return redisTemplate.keys(cacheName+"*");
    }

}
